import 'package:flutter/material.dart';
import 'package:flutter_chat_ui/models/chat_opening_remarks_model.dart';
import 'package:flutter_chat_ui/pages/chat_room_controller.dart';
import 'package:flutter_chat_ui/utils/x_load_svg.dart';
import 'package:flutter_chat_ui/utils/utils.dart';
import 'package:flutter_chat_ui/views/chat_element_welcome.dart';
import 'package:flutter_markdown_plus/flutter_markdown_plus.dart';

///
/// 显示聊天内容组件
///
class ChatMessageWidget extends StatelessWidget {
  final MessageEventType eventType;
  final String? content;

  /// 欢迎消息数据
  final OpeningRemarksData? openingRemarksData;
  // 推荐问题列表
  final List<String> suggestedQuestions;

  const ChatMessageWidget({
    super.key,
    required this.eventType,
    this.content,
    this.openingRemarksData,
    this.suggestedQuestions = const [],
  });

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: eventType == MessageEventType.master ? Alignment.topRight : Alignment.topLeft,
      children: [
        Container(
          margin: eventType == MessageEventType.master ? const EdgeInsets.only(left: 65, right: 15) : const EdgeInsets.only(left: 15, right: 65),
          padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 10),
          decoration: BoxDecoration(
            color: eventType == MessageEventType.master ? const Color(0xff94ED6D) : Colors.white,
            borderRadius: BorderRadius.circular(4),
          ),
          child: _builderContentWidget(),
        ),

        /// 箭头
        Positioned(
          top: 10,
          left: eventType == MessageEventType.master ? null : 10,
          right: eventType == MessageEventType.master ? 10 : null,
          child: CustomPaint(
            size: const Size(5, 10),
            painter: _TrianglePainter(isMaster: eventType == MessageEventType.master),
          ),
        ),
      ],
    );
  }

  ///
  /// 聊天内容组件
  ///
  Widget _builderContentWidget() {
    Widget child = const SizedBox.shrink();

    if (eventType == MessageEventType.welcome) {
      child = ChatWelcomeContentWidget(
        welcomeText: openingRemarksData?.openingStatement,
        suggestedQuestions: openingRemarksData?.suggestedQuestions ?? [],
      );
    } else if (eventType == MessageEventType.master) {
      child = MarkdownBody(
        data: content!,
      );
    } else if (eventType == MessageEventType.robot) {
      child = ChatUnderSuggestedQuestionsWidget(
        content: content!,
        suggestedQuestions: suggestedQuestions,
        onQuestionClick: (query) => ChatRoomController.to.sendMessage(
          query,
          conversationId: Utils.lastConversationId ?? '',
        ),
      );
    }
    return child;
  }
}

///
/// 推荐问题的机器人的回复组件
///
class ChatUnderSuggestedQuestionsWidget extends StatelessWidget {
  final String content;
  final List<String> suggestedQuestions;
  final ValueChanged<String>? onQuestionClick;

  const ChatUnderSuggestedQuestionsWidget({
    super.key,
    required this.content,
    this.suggestedQuestions = const [],
    this.onQuestionClick,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        /// 机器人回复内容
        MarkdownBody(data: content),

        /// 推荐问题
        if (suggestedQuestions.isNotEmpty)
          Container(
            margin: const EdgeInsets.only(top: 10),
            alignment: Alignment.topLeft,
            child: Wrap(
              direction: Axis.horizontal,
              spacing: 12,
              runSpacing: 5,
              alignment: WrapAlignment.start,
              children: suggestedQuestions
                  .map((text) => GestureDetector(
                        onTap: () => onQuestionClick?.call(text),
                        child: Container(
                          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(8),
                            border: Border.all(color: const Color(0xffDDDEE1), width: 0.5),
                          ),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              /// 图片
                              XSvgImage.load(
                                'icon_question',
                                width: 20,
                                height: 20,
                              ),

                              /// 问题文本。Flexible 组件可以让子组件在有多余空间时进行扩展，但不会强制填满空间。
                              const SizedBox(width: 5),
                              Flexible(
                                child: Text(
                                  '$text →'.fixAutoLines(),
                                  style: const TextStyle(
                                    color: Colors.black,
                                    fontSize: 14,
                                  ),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ))
                  .toList(),
            ),
          ),
      ],
    );
  }
}

///
/// 绘制三角形箭头
///
class _TrianglePainter extends CustomPainter {
  final bool isMaster;

  _TrianglePainter({
    this.isMaster = true,
  });

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()..color = isMaster ? const Color(0xff94ED6D) : Colors.white;
    Path path = Path();

    if (isMaster) {
      path.moveTo(0, 0);
      path.lineTo(0, size.height);
      path.lineTo(size.width, size.height / 2);
    } else {
      path.moveTo(0, size.height / 2);
      path.lineTo(size.width, 0);
      path.lineTo(size.width, size.height);
    }

    path.close();
    canvas.drawPath(path, paint);
    return;
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}
